/**
 * @file skoll.tools.shortcuts.js
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: skoll.tools.shortcuts.js 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/skins/Skoll/js/skoll.tools.shortcuts.js $
 */

/**
 * Skoll skin short-cuts manager.
 */
Skoll.tools.ShortCuts = {
	//
	// Protected properties.
	_clicks: [],
	_enabled: false,
	_triggers: [],
	//
	// Public methods.
	add: function(key, callback) {
		Skoll.tools.ShortCuts._triggers[key] = callback;
	},
	addClick: function(key, selector) {
		Skoll.tools.ShortCuts._clicks[key] = selector;
	},
	disable: function() {
		Skoll.tools.ShortCuts._enabled = false;
		Skoll.tools.log("Short cuts disabled");
	},
	enable: function() {
		Skoll.tools.ShortCuts._enabled = true;
		Skoll.tools.log("Short cuts enabled");
	},
	remove: function(key) {
		if (Skoll.tools.ShortCuts._clicks[key]) {
			delete Skoll.tools.ShortCuts._clicks[key];
		}
		if (Skoll.tools.ShortCuts._triggers[key]) {
			delete Skoll.tools.ShortCuts._triggers[key];
		}
	},
	reset: function() {
		Skoll.tools.ShortCuts._clicks = [];
		Skoll.tools.ShortCuts._enabled = false;
		Skoll.tools.ShortCuts._triggers = [];
	},
	//
	// Protected methods.
	_keyEventToText: function(event) {
		var key = (event.ctrlKey ? 'CTRL+' : '') + (event.altKey ? 'ALT+' : '') + (event.shiftKey ? 'SHIFT+' : ''), keyCode = event.keyCode, code;

		if (keyCode >= 96 && keyCode <= 105) {
			keyCode = keyCode - 48;
			code = String.fromCharCode(keyCode);
		} else {
			switch (event.keyCode) {
				case 27:
					code = "ESC";
					break;
				case 106:
					code = "*";
					break;
				case 107:
					code = "+";
					break;
				case 109:
					code = "-";
					break;
				case 110:
					code = ".";
					break;
				case 111:
					code = "/";
					break;
				default:
					code = String.fromCharCode(event.keyCode);
					break;
			}
		}

		return key + code;
	},
	_trigger: function(event) {
		if (Skoll.tools.ShortCuts._enabled) {
			Skoll.tools.log(Skoll.tools.ShortCuts._keyEventToText(event));
			var key = Skoll.tools.ShortCuts._keyEventToText(event);

			if (typeof Skoll.tools.ShortCuts._clicks[key] != "undefined") {
				$(Skoll.tools.ShortCuts._clicks[key]).trigger("click");
				Skoll.tools.preventDefault(event);
			} else if (typeof Skoll.tools.ShortCuts._triggers[key] != "undefined") {
				Skoll.tools.ShortCuts._triggers[key](key, event);
				Skoll.tools.preventDefault(event);
			}
		}
	}
};

$(document).ready(function() {
	$(".avoid-shortcuts").focusin(Skoll.tools.ShortCuts.disable).focusout(Skoll.tools.ShortCuts.enable);
});
